<?php

require_once($ROOT_DIR_PATH . 'lib/phpthumblib/ThumbLib.inc.php');

class generalFunction {

    public function getCurrentScriptName() {
	$scriptArray = explode('/', $_SERVER['SCRIPT_NAME']);
	if (count($scriptArray) > 0) {
	    $script_name = end($scriptArray);
	    return $script_name;
	}
	return '';
    }

    public function detect_mobile() {
	if (preg_match('/(alcatel|amoi|android|avantgo|blackberry|benq|cell|cricket|docomo|elaine|htc|iemobile|iphone|ipaq|ipod|j2me|java|midp|mini|mmp|motorola|nec-|nokia|palm|panasonic|philips|phone|playbook|sagem|sharp|sie-|silk|smartphone|sony|symbian|t-mobile|telus|up\.browser|up\.link|vodafone|wap|webos|wireless|xda|xoom|zte)/i', $_SERVER['HTTP_USER_AGENT'])) {
	    return "MOBILE";
	} else if (preg_match('/(ipad)/i', $_SERVER['HTTP_USER_AGENT'])) {
	    return "IPAD";
	} else {
	    return "BROWSER";
	}
    }

    public function navigationArray($key = '') {
	$navigationArray = Array();
	$navigationArray['home'] = Array('dashboard.php');
	$navigationArray['preference'] = Array('preference.php', 'changepassword.php', 'changeemail.php');
	$navigationArray['user'] = Array('user.php', 'userlisting.php',);
	$navigationArray['content'] = Array('content.php', 'contentlisting.php',);
	$navigationArray['banner'] = Array('banner.php', 'bannerlisting.php',);
	$navigationArray['category'] = Array('category.php', 'categorylisting.php',);
	$navigationArray['emailtemplate'] = Array('emailtemplate.php', 'emailtemplatelisting.php',);
	$navigationArray['logout'] = Array('logout.php');
	$navigationArray['dashboard'] = Array('dashboard.php');
	$navigationArray["dealersgroup"] = Array("dealersgroup.php", "dealersgrouplisting.php");
	$navigationArray["product"] = Array("product.php", "productlisting.php", "productgallery.php");
	$navigationArray["newsletter"] = Array("newsletter.php");
	
	

	if (array_key_exists($key, $navigationArray)) {
	    return $this->navigationSelector($navigationArray[$key]);
	}
	return $this->navigationSelector($navigationArray['home']);
    }

    public function navigationSelector($currentScriptArray = Array()) {
	if (in_array($this->getCurrentScriptName(), $currentScriptArray)) {
	    return true;
	}
	return false;
    }

    public function allowedImageFormats() {
	$imageAllowedFormat = Array(
	    "image/gif",
	    "image/pjpeg",
	    "image/jpeg",
	    "image/jpg",
	    "image/png",
	    "image/x-png",
	    "image/gif"
	);
	return $imageAllowedFormat;
    }

    public function image_validate($imageAllowedFormat, $image = 'image') {
	if (!$_FILES) {
	    return false;
	}
	
	if (count($_FILES[$image]['name']) == 1) {
	    if (!in_array($_FILES[$image]['type'], $imageAllowedFormat)) {
		return 'IMPROPER_FORMAT';
	    }
	    $image_array_size = Array();
	    $image_array_size = getimagesize($_FILES[$image]['tmp_name']);
	    $image_height = $image_array_size['0'];
	    $image_width = $image_array_size['1'];
	} else {
	    foreach ($_FILES[$image]['name'] as $key => $value) {
		if ($_FILES[$image]['tmp_name'][$key] == '') {
		    return 'UN_UPLOADED';
		}
		if (!in_array($_FILES[$image]['type'][$key], $imageAllowedFormat)) {
		    return 'IMPROPER_FORMAT';
		}
	    }
	}
	return 'OK';
    }

    public function file_validate($allowedFileFormat, $document = 'document') {
	if (!$_FILES) {
	    return false;
	}
	if (count($_FILES[$document]['name']) == 1) {
	    if (!in_array($_FILES[$document]['type'], $allowedFileFormat)) {
		return 'IMPROPER_FORMAT';
	    }
	} else {
	    foreach ($_FILES[$document]['name'] as $key => $value) {
		if ($_FILES[$document]['tmp_name'][$key] == '') {
		    return 'UN_UPLOADED';
		}
		if (!in_array($_FILES[$document]['type'][$key], $allowedFileFormat)) {
		    return 'IMPROPER_FORMAT';
		}
	    }
	}
	return 'OK';
    }

    public function moveImageObject($dataArray = Array()) {
	global $DBOBJ;
	if (!$_FILES)
	    return false;
	if (count($dataArray) <= 0) {
	    return false;
	}
	$image = $dataArray['image'];
	$id = $dataArray['id'];
	$image_path = $dataArray['target_path'];
	$imageObj = $dataArray['imageObj'];
	$type = $dataArray['type'];
	$imageType = $_FILES[$image]['type'];
	switch ($imageType) {
	    case "image/gif":
		$extention = '.gif';
		break;
	    case "image/pjpeg":
	    case "image/jpeg":
	    case "image/jpg":
		$extention = '.jpg';
		break;

	    case "image/png":
	    case "image/x-png":
		$extention = '.png';
		break;
	}
	$filename = '';
	$target_path = '';
	$tmp_name = '';
	$filename = '';
	$isPrimary = '';
	$filename = uniqid() . $extention;
	$thumb_filename = "thumb_" . $filename;
	$medium_filename = "medium_" . $filename;

	$tmp_name = $_FILES[$image]['tmp_name'];
	$target_path = $image_path . $filename;
	if (move_uploaded_file($tmp_name, $target_path)) {
	
	    
	    $thumb = PhpThumbFactory::create($target_path);

	    if ($type == 'banner') {
			$imageObj->updateImage($id, $filename);
			$thumb->resize(180, 170);
			$extentionType = str_replace('.', '', $extention);
			$thumb->save('../upload/images/banner/' . $thumb_filename, $extentionType);
			return $thumb_filename ;
	    } else if ($type == 'product') {
			$imageObj->updateImage($id, $filename);
			
			#########
			
			$medium = PhpThumbFactory::create($target_path);
			$medium->resize(232, 174);
			$medium->save('../upload/images/product/' . $medium_filename, $extentionType);
			
			$thumb->resize(133, 100 );
			$extentionType = str_replace('.', '', $extention);
			$thumb->save('../upload/images/product/' . $thumb_filename, $extentionType);
			
			#########
			
			return $thumb_filename ;
		} else if ($type == 'productgallery') {
		
			#########
			
			
			$imageObj->updateImage($id, $filename);
			
			$thumb->resize(180, 170);
			$extentionType = str_replace('.', '', $extention);
			$thumb->save('../upload/images/product/' . $thumb_filename, $extentionType);
			
			$medium = PhpThumbFactory::create($target_path);
			$medium->resize(232, 174);
			$medium->save('../upload/images/product/' . $medium_filename, $extentionType);
			
			#########
			
			return $thumb_filename ;
		} 
		
	}
    }

    public function moveFileObject($dataArray = Array()) {
	global $DBOBJ;
	if (!$_FILES)
	    return false;
	if (count($dataArray) <= 0) {
	    return false;
	}
	$file = $dataArray['file'];
	$id = $dataArray['id'];
	$file_path = $dataArray['target_path'];
	$fileObj = $dataArray['fileObj'];
	$fileType = $_FILES[$file]['type'];
	switch ($fileType) {
	    case "application/pdf":
		$extention = '.pdf';
		break;
	}
	$filename = '';
	$target_path = '';
	$tmp_name = '';
	$filename = '';
	$isPrimary = '';
	$filename = uniqid() . $extention;
	$tmp_name = $_FILES[$file]['tmp_name'];
	$target_path = $file_path . $filename;
	if (move_uploaded_file($tmp_name, $target_path)) {
	    $fileObj->updateFile($id, $filename);
	}
    }

    public function createThumb($dataArray = Array()) {
	if (count($dataArray) <= 0) {
	    return;
	}
	$ImageHandler = $dataArray['ImageHandler'];
	$imagePath = $dataArray['imagePath'];

	$max_width = $dataArray['max_width'];
	$filename = $dataArray['filename'];
	$thumbFilename = $dataArray['thumb_name'];
	if (file_exists($imagePath . $filename)) {
	    $folder = '../upload/images/banner/';
	    $folder = $imagePath;
	    $imageName = $filename;
	    $imagePath = $folder . $imageName;
	    $ImageDestination = $folder . $thumbFilename;
	    $width = $ImageHandler->getWidth($imagePath);
	    $height = $ImageHandler->getHeight($imagePath);
	    //Scale the image if it is greater than the width set above
	    if ($width > $max_width) {
		$scale = $max_width / $width;
	    } else {
		$scale = 1;
	    }
	    $uploaded = $ImageHandler->resizeImage($imagePath, $width, $height, $scale, $ImageDestination);
	}
    }

    public function searchfilter($searchString) {
	$search_array = Array('%', '_');
	$replace_array = Array('\%', '\_');
	return str_replace($search_array, $replace_array, $searchString);
    }

    public function cleanfilter($searchString) {
	$search_array = Array('\%', '\_');
	$replace_array = Array('%', '_');
	return str_replace($search_array, $replace_array, $searchString);
    }

    public function filter($array = '', $filterArray = Array()) {
	/*
	  for the filter array the value with  following key will call following functionms
	  mysqlRealEscape => mysql_real_escape_string
	  htmlEntityDecode => html_entity_decode
	  htmlEntity => htmlentities
	  trim => TrimElement
	  stripslashes => StripSlashElement
	 */
	foreach ($filterArray as $filterType) {
	    if (is_array($array)) {
		$array = array_map($filterType, $array);
	    } else {
		$array = $filterType($array);
	    }
	}
	return $array;
    }

    public function redirect($url) {
	if ($url == '') {
	    echo "redirect url cannot be empty";
	    exit;
	}
	header('Location: ' . $url);
	exit;
    }

    public function isLoggedIn() {
	if ($_SESSION) {
	    if (isset($_SESSION[SESSION_NAME]['admin']['userid']) && $_SESSION[SESSION_NAME]['admin']['userid'] != '') {
		return true;
	    }
	}
	return false;
    }

    public function LogOut() {

	if ($_SESSION) {
	    unset($_SESSION[SESSION_NAME]['admin']);
	    unset($_SESSION['KCFINDER']);
	}
	$url = $ADMIN_BASE_HREF . "login.php";
	$this->redirect($url);
	exit;
    }
	
	public function isAdminLogin() {
		if ($_SESSION[SESSION_NAME]['admin']['ROLE'] == 'ADMIN') {
			return true;
		} else {
			return false;
		}
	}

    public function set_session($data) {

	$_SESSION[SESSION_NAME]['admin']['userid'] = $data['userid'];
	$_SESSION[SESSION_NAME]['admin']['username'] = $data['username'];
	$_SESSION[SESSION_NAME]['admin']['firstname'] = $data['firstname'];
	$_SESSION[SESSION_NAME]['admin']['lastname'] = $data['lastname'];
	$_SESSION[SESSION_NAME]['admin']['email'] = $data['email'];
	$_SESSION[SESSION_NAME]['admin']['ROLE'] = $data['ROLE'];
	$_SESSION['KCFINDER'] = array('disabled' => false);
    }

    public function ValidUrl($url) {
	$regex = "((https?|ftp)\:\/\/)?"; // SCHEME
	$regex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?"; // User and Pass
	$regex .= "([a-z0-9-.]*)\.([a-z]{2,3})"; // Host or IP
	$regex .= "(\:[0-9]{2,5})?"; // Port
	$regex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?"; // Path
	$regex .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?"; // GET Query
	$regex .= "(#[a-z_.-][a-z0-9+\$_.-]*)?"; // Anchor
	$pattern = '/^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&amp;?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/';
	if (preg_match("/^$regex$/", $url)) {
	    return true;
	}
	return false;
    }

    public function ValidEmailAddress($EmailAddress) {
	if (!preg_match("/^[a-z0-9._-]+@[a-z0-9.-]+\.[a-z]{2,6}$/i", $EmailAddress)) {
	    return false;
	}
	return true;
    }

    public function ValidAlphaNumeric($name) {
	if (!preg_match("/^[a-zA-Z0-9 _-]+$/", $name)) {
	    return false;
	}
	return true;
    }

    public function isNumeric($n) {
	if (!preg_match("/^[0-9]+$/", $n)) {
	    return false;
	}
	return true;
    }

    public function isFloat($string) {
	if (!preg_match("/^[0-9]+(.[0-9]+)?$/", $string)) {
	    return false;
	}
	return true;
    }

    public function ValidatePassword($Pwd) {
	if (strlen($Pwd) < 5) {
	    return false;
	}
	return true;
    }

    public function IsValidDate($str) {
	$stamp = strtotime($str);

	if (!is_numeric($stamp)) {
	    return FALSE;
	}
	$month = date('m', $stamp);
	$day = date('d', $stamp);
	$year = date('Y', $stamp);

	if (checkdate($month, $day, $year)) {
	    return TRUE;
	}

	return FALSE;
    }

    public function IsGreaterDate($date, $expiry_date) {
	$date = strtotime($date);
	$expiry_date = strtotime($expiry_date);
	if ($expiry_date > $date) {
	    return FALSE;
	}
	return TRUE;
    }

    public function IsEmpty($value='') {
	if (trim($value) == '') {
	    return true;
	}
	return false;
    }

    public function clearSessionErrorMessages() {
	if ($_SESSION) {
	    if (isset($_SESSION['error'])) {
		unset($_SESSION['error']);
	    }
	}
    }

}

function pr($array, $exit = false) {
    echo "<pre>";
    print_R($array);
    echo "</pre>";
    if ($exit) {
	exit;
    }
}

function mysqlRealEscape($str = '') {
    if ($str == '') {
	return;
    }
    return mysql_real_escape_string($str);
}

function htmlEntityDecode($str = '') {
    if ($str == '') {
	return;
    }
    return htmlspecialchars_decode($str, ENT_QUOTES);
}

function htmlEntity($str = '') {
    if ($str == '') {
	return;
    }
    return htmlspecialchars($str, ENT_QUOTES);
}

function utfencode($str = '') {
    if ($str == '') {
	return;
    }
    return utf8_encode($str);
}

function utfdecode($str = '') {
    if ($str == '') {
	return;
    }
    return utf8_decode($str);
}

function addslash($str = '') {
    if ($str == '') {
	return;
    }
    return addslashes($str);
}

function stripslash($str = '') {
    if ($str == '') {
	return;
    }
    return stripslashes($str);
}

function TrimElement($str = '') {
    if ($str == '') {
	return;
    }
    return trim($str);
}

function StripSlashElement($str = '') {
    if ($str == '') {
	return;
    }
    return stripslashes($str);
}

function recursivEncodeArray(&$array = array()) {

    foreach ($array as $key => $value) {
	if (is_array($value)) {
	    recursivEncodeArray($array[$key]);
	} else {
	    $array[$key] = utf8_decode($array[$key]);
	}
    }
}

function getCollapseText($_text, $_length=150) {
    if (strlen($_text) > $_length) {
	$_temp_text = substr($_text, 0, $_length);
	$_temp_text .="...";
	return $_temp_text;
    } else {
	return $_text;
    }
}

function uploadFile($file, $destinationPath, $allowType=array(), $allowSize=2048) {

    if ($file['error'] == 1) {
	return array('', 'Unspecified Error in file upload');
    }
    if (!$file['name'])
	return array('', 'No file specified');

    $allowSize = $allowSize * 1024;
    $file_name = $file['name'];
    $file_type = $file['type'];
    $file_size = $file['size'];
    $ext_arr = preg_split("/\./", basename($file_name));
    $file_ext = strtolower($ext_arr[count($ext_arr) - 1]);

    $uniqer = substr(md5(uniqid(rand(), 1)), 0, 5);
    $file_name = $uniqer . '_' . str_replace(" ", "_", $file_name);

    if (count($allowType) > 0) {
	$lowerAllowType = array();
	foreach ($allowType as $key => $val) {
	    $lowerAllowType[$key] = strtolower($val);
	}

	if (in_array($file_ext, $lowerAllowType)

	    );
	else {
	    $result = "'" . $file['name'] . "' is not a valid file."; //Show error if any.
	    return array('', $result);
	}
    }

    if ($file_size > $allowSize) {
	return array('', 'You have exceeded the file size limit.');
    }

    $uploadfile = $destinationPath . $file_name;

    $result = '';
    //Move the file from the stored location to the new location
    if (!@move_uploaded_file($file['tmp_name'], $uploadfile)) {
	$result = "Cannot upload the file '" . $file['name'] . "'"; //Show error if any.
	if (!file_exists($destinationPath)) {
	    $result .= " : Folder don't exist.";
	} elseif (!is_writable($destinationPath)) {
	    $result .= " : Folder not writable.";
	} elseif (!is_writable($uploadfile)) {
	    $result .= " : File not writable.";
	}
	$file_name = '';
    }
    return array($file_name, $result);
}

function dl_file($file) {

    //First, see if the file exists
    if (!is_file($file)) {
	die("<div style='text-align:center;'><h1> Sorry, file temporary not available!</h1></div>");
    }

    //Gather relevent info about file
    $len = filesize($file);
    $filename = basename($file);
    $file_extension = strtolower(substr(strrchr($filename, "."), 1));

    //This will set the Content-Type to the appropriate setting for the file
    switch ($file_extension) {
	case "pdf": $ctype = "application/pdf";
	    break;
	case "exe": $ctype = "application/octet-stream";
	    break;
	case "zip": $ctype = "application/zip";
	    break;
	case "doc": $ctype = "application/msword";
	    break;
	case "xls": $ctype = "application/vnd.ms-excel";
	    break;
	case "ppt": $ctype = "application/vnd.ms-powerpoint";
	    break;
	case "gif": $ctype = "image/gif";
	    break;
	case "png": $ctype = "image/png";
	    break;
	case "jpeg":
	case "jpg": $ctype = "image/jpg";
	    break;
	case "mp3": $ctype = "audio/mpeg";
	    break;
	case "wav": $ctype = "audio/x-wav";
	    break;
	case "mpeg":
	case "mpg":
	case "mpe": $ctype = "video/mpeg";
	    break;
	case "mov": $ctype = "video/quicktime";
	    break;
	case "avi": $ctype = "video/x-msvideo";
	    break;

	//The following are for extensions that shouldn't be downloaded (sensitive stuff, like php files)
	case "php":
	case "htm":
	case "html":
	case "txt": die("<b>Cannot be used for " . $file_extension . " files!</b>");
	    break;

	default: $ctype = "application/force-download";
    }

    //Begin writing headers
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: public");
    header("Content-Description: File Transfer");

    //Use the switch-generated Content-Type
    header("Content-Type: $ctype");

    //Force the download
    //$header="Content-Disposition: attachment; filename=".$filename.";"; //for force fully download
    $header = "Content-Disposition: inline; filename=" . $filename . ";";
    header($header);
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: " . $len);
    @readfile($file);
    exit;
}

?>

